package com.tsfyun.scm.config.ws;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.tsfyun.common.base.exception.ServiceException;
import com.tsfyun.common.base.util.StringUtils;
import com.tsfyun.common.base.validator.ValidatorUtils;
import com.tsfyun.scm.dto.support.WsMessageDTO;
import com.tsfyun.scm.entity.system.SysMenu;
import com.tsfyun.scm.service.system.ISysMenuService;
import com.tsfyun.scm.service.user.IPersonService;
import com.tsfyun.scm.vo.user.SimplePersonInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * websocket发送消息
 */
@Slf4j
@Component
public class WsBiz {

    @Autowired
    private ISysMenuService sysMenuService;

    @Autowired
    private IPersonService personService;

    @Resource
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;


    @Autowired
    private RedisTemplate redisTemplate;

    public void send2Client(WsMessageDTO wsMessageDTO) {
        Optional.ofNullable(wsMessageDTO).orElseThrow(()->new ServiceException("推送消息不能为空"));
        ValidatorUtils.validateEntity(wsMessageDTO,null);
        //如果不是广播且操作码为空，则收件人不能为空
        if(!Objects.equals(wsMessageDTO.getIsBroad(),Boolean.TRUE)
                && StringUtils.isEmpty(wsMessageDTO.getOperationCode())
                && CollUtil.isEmpty(wsMessageDTO.getUserIds())) {
            throw new ServiceException("消息接收人不能为空");
        }
        //如果操作码不为空，则单据类型和单据id必传
        if(StringUtils.isNotEmpty(wsMessageDTO.getOperationCode())
            && (StringUtils.isEmpty(wsMessageDTO.getDocumentType()) || StringUtils.isEmpty(wsMessageDTO.getDocumentId()))) {
            throw new ServiceException("单据类型和单据id不能为空");
        }
        if(StringUtils.isNotEmpty(wsMessageDTO.getOperationCode())) {
            wsMessageDTO.setNoticeClient(Boolean.TRUE);
        }
        //如果操作码不为空，获取对应的接收人
        threadPoolTaskExecutor.execute(()->{
            try {
                if (CollUtil.isEmpty(wsMessageDTO.getUserIds())) {
                    if (StringUtils.isNotEmpty(wsMessageDTO.getOperationCode())) {
                        SysMenu sysMenu = sysMenuService.findByOperationCode(wsMessageDTO.getOperationCode());
                        if (Objects.nonNull(sysMenu)) {
                            //赋值跳转url
                            String menuActionUrl = sysMenu.getUrl();
                            wsMessageDTO.setHref(StringUtils.isNotEmpty(menuActionUrl) ? menuActionUrl.concat("?=id").concat(wsMessageDTO.getDocumentId()) : null);
                            wsMessageDTO.setHref(sysMenu.getUrl());
                            List<SimplePersonInfo> personInfos = personService.getPersonByMenuId(sysMenu.getId());
                            if (CollUtil.isNotEmpty(personInfos)) {
                                wsMessageDTO.setUserIds(personInfos.stream().map(SimplePersonInfo::getId).distinct().collect(Collectors.toList()));
                            }
                        }
                    }
                }
            } finally {

            }
            redisTemplate.convertAndSend(WsConstant.WS_TOPIC,JSONObject.toJSONString(wsMessageDTO));
        });
    }

}


